package com.bootdo.system.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.aliyuncs.exceptions.ClientException;
import com.bootdo.common.annotation.Log;
import com.bootdo.common.config.ApplicationContextRegister;
import com.bootdo.common.config.Constant;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.domain.Tree;
import com.bootdo.common.service.DictService;
import com.bootdo.common.service.FileService;
import com.bootdo.common.utils.MD5Utils;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.RandomUtils;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.oa.domain.NotifyDO;
import com.bootdo.oa.service.NotifyRecordService;
import com.bootdo.oa.service.NotifyService;
import com.bootdo.system.dao.MyInviteDao;
import com.bootdo.system.dao.UserDao;
import com.bootdo.system.domain.MenuDO;
import com.bootdo.system.domain.MyInviteDO;
import com.bootdo.system.domain.PayDeatailsDO;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.domain.UserpicDO;
import com.bootdo.system.service.MenuService;
import com.bootdo.system.service.PayDeatailsService;
import com.bootdo.system.service.SuyongService;
import com.bootdo.system.service.UserOldService;
import com.bootdo.system.service.UserService;
import com.bootdo.system.service.UserpicService;

@Controller
public class LoginController extends BaseController {

	@Autowired
	MenuService menuService;
	@Autowired
	FileService fileService;
	@Autowired
	UserService userService;
	@Autowired
	NotifyService notifyService;
	@Autowired
	NotifyRecordService notifyRecordService;
	@Autowired
	DictService dickService;
	@Autowired
	UserOldService useroldService;
	@Autowired
	SuyongService suyongService;
	@Autowired
	UserpicService userpicService;
	@Autowired 
	MyInviteDao  myInviteDao;
	@Autowired
	PayDeatailsService payDeatailsService;
	

	/*
	 * @GetMapping({ "/", "" }) String welcome(Model model) {
	 * 
	 * return "redirect:/login"; }
	 */
	
	
	
	/**
	 * 微信服务号校验
	 * @return
	 */
	@GetMapping("/MP_verify_KbJazcz6PvWFI7fP.txt")
	@ResponseBody
	public String MP_verify_esLsssssUY04(){
	    return  "KbJazcz6PvWFI7fP";
	}
	
	
	/**
	 * 微信服务号校验
	 * @return
	 */
	@GetMapping("/MP_verify_4J1fSrcH41Otr5qH.txt")
	@ResponseBody
	public String MP_verify_esLsssssUY03(){
	    return  "4J1fSrcH41Otr5qH";
	}


	

	@Log("请求访问主页")
	@GetMapping({ "/index" })
	String index(Model model) {
		List<Tree<MenuDO>> menus = menuService.listMenuTree(getUserId());
		UserDO userDO = userService.get(getUserId());
		model.addAttribute("menus", menus);
		model.addAttribute("companyName", getUser().getCompanyName());
		UserpicDO user = userpicService.getUserpicByUserId(ShiroUtils.getUserId());
		if (user != null) {
			model.addAttribute("picUrl", user.getImgurl());
		} else {
			model.addAttribute("picUrl", Constant.USER_PIC);
		}
		model.addAttribute("username", getUser().getCompanyName());
		model.addAttribute("money", getUser().getWyzMoney());
		model.addAttribute("allmoney", getUser().getWyzAllmoney());
		model.addAttribute("user", userDO);
		return "index_v1";
	}

	/**
	 * @Title: mobileIndex
	 * @Description: TODO(移动端跳转主页的方法)
	 * @author: lzy
	 * @date: 2018年5月31日 上午11:52:45
	 */
	@Log("请求访问移动端主页")
	@ResponseBody
	@GetMapping({ "/mobileIndex" })
	R mobileIndex(Model model) {
		UserDO user = (UserDO) SecurityUtils.getSubject().getPrincipal();
		try {
			UserDO userDO = userService.get(user.getId());
			return R.ok("" + userDO.getFirstlogin() + "");
		} catch (Exception e) {
			return R.error("no");
		}

	}

	/**
	 * @Title: login
	 * @Description: TODO(跳转登录界面的方法)
	 * @author: lzy
	 * @date: 2018年5月10日 上午10:59:06
	 */
	@GetMapping("/login")
	String login() {

		return "login";
	}

	@GetMapping("/register")
	String register() {
		return "register";
	}

	@GetMapping("/forget")
	String forget() {
		return "findPassword";
	}

	@PostMapping("/forgetOne")
	String forgetOne(Model model, ShiroHttpServletRequest request) {
		String parameter = request.getParameter("phone");
		model.addAttribute("phone", parameter);
		return "findpwd";
	}
   
	
	
	@PostMapping("/sendMsg")
	@ResponseBody
	public Map<String, Object> sendMsg(ShiroHttpServletRequest request) throws Exception {
		String phoneNumber = request.getParameter("phone");
		Map<String, Object> map = new HashMap<>();
		map.put("phone", phoneNumber);
		boolean exit = userService.noexit(map);
		if (exit == false) {
			return R.error("手机号码不存在");
		}
		Map<String, Object> resultMap;
		String code = RandomUtils.codeNum();
		try {
			SmsController.sendSms(phoneNumber, code);
			resultMap = new HashMap<>();
			resultMap.put("code", code);
			resultMap.put("msg", "发送成功");
			HttpSession session = request.getSession();
			session.setAttribute("smscode", code);
			session.setMaxInactiveInterval(3 * 60);
			return resultMap;
		} catch (ClientException e) {
			return R.error();

		}
	}

	@PostMapping("/sendMsgRes")
	@ResponseBody
	public Map<String, Object> sendMsgRes(ShiroHttpServletRequest request) throws Exception {
		String phoneNumber = request.getParameter("phone");
		Map<String, Object> map = new HashMap<>();
		map.put("phone", phoneNumber);
		boolean exit = userService.exit(map);
		if (exit == false) {
			return R.error("手机号码已存在");
		}
		Map<String, Object> resultMap;
		String code = RandomUtils.codeNum();
		try {
			SmsController.sendSms(phoneNumber, code);
			resultMap = new HashMap<>();
			resultMap.put("code", code);
			resultMap.put("msg", "发送成功");
			HttpSession session = request.getSession();
			session.setAttribute("smscode", code);
			session.setMaxInactiveInterval(3 * 60);
			return resultMap;
		} catch (ClientException e) {
			return R.error();

		}
	}

	// TODO 普通用户注册
	@GetMapping("/register2")
	@ResponseBody
	public Map<String, Object> register(String companyName, String phone, String code, String password,
			String inviteCode, ShiroHttpServletRequest request) {
		Long[] SYS_NOTITY = {Constant.SYS_NOTITY};
		UserDO userDO = new UserDO();
		userDO.setCompanyName(companyName);
		userDO.setAddTime(new Date());
		userDO.setPassword(password);
		userDO.setPhone(phone);
		userDO.setAgencyRank(0);
		userDO.setDelflag(0);
		HttpSession session = request.getSession();
		String smscode = (String) session.getAttribute("smscode");
		if (StringUtils.isEmpty(smscode) || !smscode.equals(code)) {
			return R.error("验证码未发送或验证码错误");
		}
		List<UserDO> list = null;
		UserDO myupperUser =null;
		Long userId = null;
		if(StringUtils.isEmpty(inviteCode)){
			myupperUser=useroldService.get(Constant.AGENT_ONE);
			userId = myupperUser.getId();
		}else {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("inviteCode", inviteCode);
			if (useroldService.list(map).size() > 0) {
				list = useroldService.list(map);
				myupperUser = list.get(0);// 得到推荐者对象
				userId = myupperUser.getId();
			}else {
				return R.error("推荐码有误,或不存在");
			}
		}
	
		if (myupperUser.getAgencyRank() == 0) {// 判断如果推荐者是客户等级
			// 则推荐给他的上级
			long myupper = myupperUser.getMyupper();
			UserDO userDO2;
			if(myupper == 0){
				userDO2 = useroldService.get(Constant.SQL_NUMBER);//推荐者上级
				userDO.setMyupper(Constant.SQL_NUMBER);
			}else {
				userDO2 = useroldService.get(myupper);//推荐者上级
				userDO.setMyupper(myupper);
			}
			Long[] userIds = { userId };
			int i = useroldService.save(userDO);
			//我的邀请开始
			MyInviteDO myInviteDO = new MyInviteDO();
			myInviteDO.setAddTime(new Date());
			myInviteDO.setInviteId(userDO.getId());
			myInviteDO.setUserId(userId);
			myInviteDO.setSign(0);
			myInviteDao.save(myInviteDO);
			// 注册成功推送消息
			Long[] userid = {userDO.getId()};
			NotifyDO notify = new NotifyDO();
			notify.setType("1");
			notify.setStatus("1");
			notify.setCreateDate(new Date());
			notify.setTitle("注册通知！");
			notify.setCreateBy(Constant.SQL_NUMBER);
			notify.setUserIds(userid);
			notify.setContent("欢迎注册速用科技管理后台，感谢你的支持。");
			notify.setRemarks("速用币充值请联系你的邀请人");
			notifyService.save(notify);
			if (i == 1) {
				// 推送给邀请人的模板
				NotifyDO notify1 = new NotifyDO();
				notify1.setType("1");
				notify1.setStatus("1");
				notify1.setCreateDate(new Date());
				notify1.setTitle("邀请通知！");
				notify1.setCreateBy(Constant.SQL_NUMBER);
				notify1.setUserIds(userIds);
				notify1.setContent("你邀请的小伙伴(" + companyName + ":"+phone+")已经推荐给你的上级代理，可在我的邀请中查看邀请记录，感谢你的支持，成为代理即可拥有下级的功能并能享有超额返利！！");
				long money = myupperUser.getWyzMoney() + Integer.parseInt(dickService.getValue(Constant.DIC_COIN));
				UserDO user = new UserDO();
				user.setId(userId);
				user.setWyzMoney(money);
				useroldService.update(user);
				notify1.setRemarks("邀请一个小伙伴注册成功速用币+" + Integer.parseInt(dickService.getValue(Constant.DIC_COIN)));
				//速用币明细表记录开始
				resDeatailsForSupport(userId,money,(long)Integer.parseInt(dickService.getValue(Constant.DIC_COIN)));
				//速用币明细表记录结束
				notifyService.save(notify1);
				// 推送给推荐人上级的模板
				NotifyDO notify2 = new NotifyDO();
				notify2.setType("1");
				notify2.setStatus("1");
				notify2.setCreateDate(new Date());
				notify2.setTitle("邀请通知");
				notify2.setCreateBy(Constant.SQL_NUMBER);
				if(myupper == 0){
					Long[] upperIds ={Constant.SQL_NUMBER};
					notify2.setUserIds(upperIds);
				}else {
					Long[] upperIds ={myupper};
					notify2.setUserIds(upperIds);
				}
				
				notify2.setContent(
						"你的下级(" + myupperUser.getCompanyName() + ")邀请一个小伙伴注册成功了，尽快和你的小伙伴(" + companyName + ":"+phone+")取得联系哦！！");
				notify2.setRemarks("走向成功的捷径就是抓住每一个机会");
				notifyService.save(notify2);
				// 推荐给系统消息管理员的模板
				NotifyDO notify22 = new NotifyDO();
				notify22.setType("1");
				notify22.setStatus("1");
				notify22.setCreateDate(new Date());
				notify22.setTitle("网页邀请通知");
				notify22.setCreateBy(Constant.SQL_NUMBER);
				notify22.setUserIds(SYS_NOTITY);
				notify22.setContent("邀请人->"+myupperUser.getCompanyName()+"("+myupperUser.getPhone()+")因该邀请人为客户 ,新注册用户->"+companyName+"("+phone+")已转移到上级代理->"+userDO2.getCompanyName()+"("+userDO2.getPhone()+")");
				notifyService.save(notify22);
				
				return R.ok("注册成功");
			} else {
				return R.error("操作失败");
			}

		} else {// 推荐者是代理级别直接推荐消息
			Long[] userIds = { userId };
			userDO.setMyupper(userId);
			int i = useroldService.save(userDO);
			// 注册成功推送鸡血消息
			Long[] userid = { userDO.getId() };
			NotifyDO notify = new NotifyDO();
			notify.setCreateDate(new Date());
			notify.setTitle("注册通知！");
			notify.setCreateBy(Constant.SQL_NUMBER);
			notify.setUserIds(userid);
			notify.setContent("欢迎注册速用科技管理后台，感谢你的支持。");
			notify.setRemarks("速用币充值请联系你的邀请人.");
			notifyService.save(notify);
			//我的邀请开始
			MyInviteDO myInviteDO = new MyInviteDO();
			myInviteDO.setAddTime(new Date());
			myInviteDO.setInviteId(userDO.getId());
			myInviteDO.setUserId(userId);
			myInviteDO.setSign(0);
			myInviteDao.save(myInviteDO);
			if (i == 1) {
				long money = myupperUser.getWyzMoney() + Integer.parseInt(dickService.getValue(Constant.DIC_COIN));
				UserDO user = new UserDO();
				user.setId(userId);
				user.setWyzMoney(money);
				useroldService.update(user);
				// 推送给代理的模板
				NotifyDO notify6 = new NotifyDO();
				notify6.setCreateDate(new Date());
				notify6.setTitle("邀请通知！");
				notify6.setCreateBy(Constant.SQL_NUMBER);
				notify6.setUserIds(userIds);
				notify6.setContent("你邀请的小伙伴(" + companyName + ":"+phone+")注册成功了，尽快和你的小伙伴取得联系哦！！");
				notify6.setRemarks("邀请一个小伙伴注册成功速用币+" + Integer.parseInt(dickService.getValue(Constant.DIC_COIN)));
				//速用币明细表记录开始
				resDeatailsForSupport(userId,money,(long)Integer.parseInt(dickService.getValue(Constant.DIC_COIN)));
				//速用币明细表记录结束
				notifyService.save(notify6);
				// 推荐给系统消息管理员的模板
				NotifyDO notify66 = new NotifyDO();
				notify66.setType("1");
				notify66.setStatus("1");
				notify66.setCreateDate(new Date());
				notify66.setTitle("网页邀请通知");
				notify66.setCreateBy(Constant.SQL_NUMBER);
				notify66.setUserIds(SYS_NOTITY);
				notify66.setContent("邀请人->"+myupperUser.getCompanyName()+"("+myupperUser.getPhone()+"),新注册用户->"+companyName+"("+phone+")");
				notifyService.save(notify66);
				return R.ok("注册成功");
			} else {
				return R.error("操作失败");
			}
		}
	}
    
	//速用币明细之注册送币封装方法
	public  void resDeatailsForSupport(long userId,Long sum,Long coin){
		PayDeatailsDO payDeatailsDO = new PayDeatailsDO();
		payDeatailsDO.setUserId(userId);
		payDeatailsDO.setDeatailsTime(new Date());
		payDeatailsDO.setDeatailsType("邀请注册送速用币");
		payDeatailsDO.setDeatailsSupport(coin);
		payDeatailsDO.setSum(sum);
		payDeatailsService.save(payDeatailsDO);
	}
	

	// TODO 账号密码 短信验证登录
	@Log("登录")
	@PostMapping("/login")
	@ResponseBody
	R ajaxLogin(String phone, String password, String smsphone, String sms_num, HttpServletRequest request,
			Boolean rememberme) {
		if (rememberme == null) {
			rememberme = false;
		}
		if (password != null && password != "") {
			Map<String, Object> map = new HashMap<>();
			map.put("phone", phone);
			if (userService.noexit(map) == false) {
				return R.error("手机号码不存在");
			}
			UsernamePasswordToken token = new UsernamePasswordToken(phone, password, rememberme);
			Subject subject = SecurityUtils.getSubject();
			try {
					subject.login(token);
					return R.ok();
				} catch (AuthenticationException e) {
					return R.error(e.getMessage());
				}


		} else {
			Map<String, Object> map = new HashMap<>();
			map.put("phone", smsphone);
			UserDO userOld = null;
			try {
				userOld = useroldService.list(map).get(0);
			} catch (Exception e) {
			}

				if (userOld == null) {
					return R.error("手机号码不存在");
				} else {
					HttpSession session = request.getSession();
					String code = (String) session.getAttribute("smscode");
					if (!sms_num.equals(code)) {
						return R.error("验证码错误");
					}
					String oldpwd = userOld.getPassword();
					UsernamePasswordToken token = new UsernamePasswordToken(smsphone, oldpwd);
					Subject subject = SecurityUtils.getSubject();
					try {
						subject.login(token);
						return R.ok();
					} catch (AuthenticationException e) {
						return R.error(e.getMessage());
					}

				}

		}

	}
	

	@GetMapping("/logout")
	String logout() {
		ShiroUtils.logout();
		return "redirect:/login";
	}

	/**
	 * 
	 * @Title: logout
	 * @Description: TODO(移动端退出登录)
	 * @author: lzy
	 * @date: 2018年6月6日 下午5:55:13
	 */
	@GetMapping("/loginoutapp")
	@ResponseBody
	R logoutmobile() {
		ShiroUtils.logout();
		return R.ok("success");
	}

	// 推荐注册跳转页面
	@GetMapping("/r/{code}")
	String inviteRegister(Model model, @PathVariable("code") String code) {
		model.addAttribute("code", code);
		return "inviteRegister";
	}

	/**
	 * @Title: share
	 * @Description: TODO(PC跳转分享链接的页面)
	 * @author: lzy
	 * @date: 2018年5月16日 上午9:31:15
	 */
	@GetMapping("/share")
	String share(Model model, ShiroHttpServletRequest request) {
		Long userId = ShiroUtils.getUserId();
		UserDO userDO = userService.get(userId);
		String code = userDO.getInviteCode();
		StringBuffer sb = new StringBuffer();
		sb.append(Constant.URL + "/r/");
		sb.append(code);
		String coin = dickService.getValue(Constant.DIC_COIN);
		String url = sb.toString();
		model.addAttribute("url", url);
		model.addAttribute("code", code);
		model.addAttribute("coin", coin);

		return "invite";
	}

	/**
	 * @Title: share
	 * @Description: TODO(移动端跳转分享链接的页面)
	 * @author: lzy
	 * @date: 2018年5月16日 上午9:31:15
	 */
	@GetMapping("/mobileshare")
	@ResponseBody
	Map<String, Object> mobileshare() {
		Long userId = null;
		try {
			userId = ShiroUtils.getUserId();
		} catch (Exception e) {
             return null;
		}
		UserDO userDO = userService.get(userId);
		String code=null;
		try {
			code= userDO.getInviteCode();
		} catch (Exception e) {
			
		}		
		StringBuffer sb = new StringBuffer();
		sb.append(Constant.URL + "/r/");
		sb.append(code);
		String coin = dickService.getValue(Constant.DIC_COIN);
		String url = sb.toString();
		Map<String, Object> map = new HashMap<>();
		map.put("url", url);
		map.put("code", code);
		map.put("coin", coin);

		return map;
	}

	// 跳转主页
	@GetMapping("/main")
	String main() {
		return "main";
	}
	
	// 跳转主页
	@GetMapping("/main1")
	String main1() {
		return "main1";
	}
	

	/**
	 * @Title: findExit
	 * @Description: TODO(查询旧数据库手机号码是否存在)
	 * @author: lzy
	 * @date: 2018年5月9日 下午3:32:34
	 */
	public static UserDO findOldExit(String phone) {
		UserDO userDO = null;
		Map<String, Object> map = new HashMap<>();
		map.put("phone", phone);
		UserDao userMapper = ApplicationContextRegister.getBean(UserDao.class);
		try {
			userDO = userMapper.list(map).get(0);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return userDO;
	}

	@PostMapping("/findPwd")
	@ResponseBody
	public static R findPwd(ShiroHttpServletRequest request) {
		String phone = request.getParameter("phone");
		UserDO userDO = null;
		Map<String, Object> map = new HashMap<>();
		map.put("phone", phone);
		UserDao userMapper = ApplicationContextRegister.getBean(UserDao.class);
		try {
			userDO = userMapper.list(map).get(0);
		} catch (Exception e) {
			// TODO: handle exception
		}
		if (userDO == null) {
			return R.error("手机号码不存在");
		}
		return R.ok();
	}

	/**
	 * @Title: forgetPhone
	 * @Description: TODO(忘记密码发送短信的方法)
	 * @author: lzy
	 * @date: 2018年5月17日 上午10:54:47
	 */
	@PostMapping("/forgetPhone")
	@ResponseBody
	static Map<String, Object> forgetPhone(ShiroHttpServletRequest request) throws ClientException {
		String phoneNumber = request.getParameter("phone");
		Map<String, Object> resultMap;
		String code = RandomUtils.codeNum();
		try {
			SmsController.sendSms(phoneNumber, code);
			resultMap = new HashMap<>();
			resultMap.put("code", code);
			resultMap.put("msg", "发送成功");
			HttpSession session = request.getSession();
			session.setAttribute("smscode", code);
			session.setMaxInactiveInterval(3 * 60);
			return resultMap;
		} catch (Exception e) {
			return R.error();

		}

	}

	/**
	 * @Title: updatePwd
	 * @Description: TODO(忘记密码更新密码的方法)
	 * @author: lzy
	 * @date: 2018年5月17日 上午11:28:49
	 */
	@PostMapping("/updatePwd")
	@ResponseBody
	public R updatePwd(ShiroHttpServletRequest request, String phone, String password, String code) {
		HttpSession session = request.getSession();
		String sms = (String) session.getAttribute("smscode");
		if (!code.equals(sms)) {
			return R.error("验证码错误");
		}
		int update = 0;
		UserDO userDO = new UserDO();
		Map<String, Object> map = new HashMap<>();
		map.put("phone", phone);
		if (userService.list(map).size() > 0) {
			userDO.setPhone(phone);
			userDO.setPassword(MD5Utils.encrypt(phone, password));
			update = userService.updatePhone(userDO);
		} else if (useroldService.list(map).size() > 0) {
			userDO.setPhone(phone);
			userDO.setPassword(password);
			update = useroldService.updatePhone(userDO);
		}
		if (update == 1) {
			return R.ok("重置成功");
		} else {
			return R.error("重置失败");
		}

	}
	
	
	// TODO  微信分享注册
	@GetMapping("/shareRegister")
	@ResponseBody
	public Map<String, Object> registerShare(String companyName, String phone,String password,
			String inviteCode, ShiroHttpServletRequest request) {
		Long[] SYS_NOTITY = {Constant.SYS_NOTITY};
		Map<String, Object> companyNameMap = new HashMap<String, Object>();
		companyNameMap.put("companyName", companyName);
		if(useroldService.list(companyNameMap).size() > 0){	
			return R.error("企业名称已存在");
		}
		Map<String, Object> phonemap = new HashMap<>();
		phonemap.put("phone",phone);
		if (useroldService.list(phonemap).size() > 0) {
			return R.error("手机号码已存在");
		}
		UserDO userDO = new UserDO();
		userDO.setCompanyName(companyName);
		userDO.setAddTime(new Date());
		userDO.setPassword(password);
		userDO.setPhone(phone);
		userDO.setAgencyRank(0);
		userDO.setDelflag(0);
		List<UserDO> list = null;
		UserDO myupperUser =null;
		Long userId = null;
		if(StringUtils.isEmpty(inviteCode)){
			myupperUser=useroldService.get(Constant.AGENT_ONE);
			userId = myupperUser.getId();
		}else {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("inviteCode", inviteCode);
			if (useroldService.list(map).size() > 0) {
				list = useroldService.list(map);
				myupperUser = list.get(0);// 得到推荐者对象
				userId = myupperUser.getId();
				
			}else {
				myupperUser=useroldService.get(Constant.AGENT_ONE);
				userId = myupperUser.getId();
			}
		}
	
		if (myupperUser.getAgencyRank() == 0) {// 判断如果推荐者是客户等级
			// 则推荐给他的上级
			long myupper = myupperUser.getMyupper();
			UserDO userDO2 = useroldService.get(myupper);
			Long[] userIds = { userId };
			Long[] upperIds = { myupper };
			if (myupper == 0) {
				userDO.setMyupper(Constant.SQL_NUMBER);
			} else {
				userDO.setMyupper(myupper);
			}
			int i = useroldService.save(userDO);
			//我的邀请开始
			MyInviteDO myInviteDO = new MyInviteDO();
			myInviteDO.setAddTime(new Date());
			myInviteDO.setInviteId(userDO.getId());
			myInviteDO.setUserId(userId);
			myInviteDO.setSign(0);
			myInviteDao.save(myInviteDO);
			// 注册成功推送消息
			Long[] userid = { userDO.getId() };
			NotifyDO notify = new NotifyDO();
			notify.setType("1");
			notify.setStatus("1");
			notify.setCreateDate(new Date());
			notify.setTitle("注册通知！");
			notify.setCreateBy(Constant.SQL_NUMBER);
			notify.setUserIds(userid);
			notify.setContent("欢迎注册速用科技管理后台，感谢你的支持。");
			notify.setRemarks("速用币充值请联系你的邀请人");
			notifyService.save(notify);
			if (i == 1) {
				// 推送给邀请人的模板
				NotifyDO notify1 = new NotifyDO();
				notify1.setType("1");
				notify1.setStatus("1");
				notify1.setCreateDate(new Date());
				notify1.setTitle("邀请通知！");
				notify1.setCreateBy(Constant.SQL_NUMBER);
				notify1.setUserIds(userIds);
				notify1.setContent("你邀请的小伙伴(" + companyName + ":"+phone+")已经推荐给你的上级代理，可在我的邀请中查看邀请记录，感谢你的支持，成为代理即可拥有下级的功能并能享有超额返利！！");
				long money = myupperUser.getWyzMoney() + Integer.parseInt(dickService.getValue(Constant.DIC_COIN));
				UserDO user = new UserDO();
				user.setId(userId);
				user.setWyzMoney(money);
				useroldService.update(user);
				notify1.setRemarks("邀请一个小伙伴注册成功速用币+" + Integer.parseInt(dickService.getValue(Constant.DIC_COIN)));
				//速用币明细表记录开始
				resDeatailsForSupport(userId,money,(long)Integer.parseInt(dickService.getValue(Constant.DIC_COIN)));
				//速用币明细表记录结束
				notifyService.save(notify1);
				// 推送给推荐人上级的模板
				NotifyDO notify2 = new NotifyDO();
				notify2.setType("1");
				notify2.setStatus("1");
				notify2.setCreateDate(new Date());
				notify2.setTitle("邀请通知");
				notify2.setCreateBy(Constant.SQL_NUMBER);
				notify2.setUserIds(upperIds);
				notify2.setContent(
						"你的下级(" + myupperUser.getCompanyName() + ")邀请一个小伙伴注册成功了，尽快和你的小伙伴(" + companyName + ":"+phone+")取得联系哦！！");
				notify2.setRemarks("走向成功的捷径就是抓住每一个机会");
				notifyService.save(notify2);
				
				// 推荐给系统消息管理员的模板
				NotifyDO notify22 = new NotifyDO();
				notify22.setType("1");
				notify22.setStatus("1");
				notify22.setCreateDate(new Date());
				notify22.setTitle("微信分享邀请通知");
				notify22.setCreateBy(Constant.SQL_NUMBER);
				notify22.setUserIds(SYS_NOTITY);
				notify22.setContent("邀请人->"+myupperUser.getCompanyName()+"("+myupperUser.getPhone()+")因该邀请人为客户 ,新注册用户->"+companyName+"("+phone+")已转移到上级代理->:"+userDO2.getCompanyName()+"("+userDO2.getPhone()+")");
				notifyService.save(notify22);
				
				return R.ok("注册成功");
			} else {
				return R.error("操作失败");
			}

		} else {// 推荐者是代理级别直接推荐消息
			Long[] userIds = { userId };
			userDO.setMyupper(userId);
			int i = useroldService.save(userDO);
			// 注册成功推送鸡血消息
			Long[] userid = { userDO.getId() };
			NotifyDO notify = new NotifyDO();
			notify.setCreateDate(new Date());
			notify.setTitle("注册通知！");
			notify.setCreateBy(Constant.SQL_NUMBER);
			notify.setUserIds(userid);
			notify.setContent("欢迎注册速用科技管理后台，感谢你的支持。");
			notify.setRemarks("速用币充值请联系你的邀请人.");
			notifyService.save(notify);
			//我的邀请开始
			MyInviteDO myInviteDO = new MyInviteDO();
			myInviteDO.setAddTime(new Date());
			myInviteDO.setInviteId(userDO.getId());
			myInviteDO.setUserId(userId);
			myInviteDO.setSign(0);
			myInviteDao.save(myInviteDO);
			if (i == 1) {
				long money = myupperUser.getWyzMoney() + Integer.parseInt(dickService.getValue(Constant.DIC_COIN));
				UserDO user = new UserDO();
				user.setId(userId);
				user.setWyzMoney(money);
				useroldService.update(user);
				// 推送给代理的模板
				NotifyDO notify6 = new NotifyDO();
				notify6.setCreateDate(new Date());
				notify6.setTitle("邀请通知！");
				notify6.setCreateBy(Constant.SQL_NUMBER);
				notify6.setUserIds(userIds);
				notify6.setContent("你邀请的小伙伴(" + companyName + ":"+phone+")注册成功了，尽快和你的小伙伴取得联系哦！！");
				notify6.setRemarks("邀请一个小伙伴注册成功速用币+" + Integer.parseInt(dickService.getValue(Constant.DIC_COIN)));
				
				// 推荐给系统消息管理员的模板
				NotifyDO notify66 = new NotifyDO();
				notify66.setType("1");
				notify66.setStatus("1");
				notify66.setCreateDate(new Date());
				notify66.setTitle("微信分享邀请通知");
				notify66.setCreateBy(Constant.SQL_NUMBER);
				notify66.setUserIds(SYS_NOTITY);
				notify66.setContent("邀请人->"+myupperUser.getCompanyName()+"("+myupperUser.getPhone()+"),新注册用户->"+companyName+"("+phone+")");
				
				
				//速用币明细表记录开始
				resDeatailsForSupport(userId,money,(long)Integer.parseInt(dickService.getValue(Constant.DIC_COIN)));
				//速用币明细表记录结束
				notifyService.save(notify66);
				notifyService.save(notify6);
				return R.ok("注册成功");
			} else {
				return R.error("操作失败");
			}
		}
	}
	

	
	

}
